﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using VO.Entities;

namespace VO.Business.Controllers
{
    public static class BadgesController
    {
        public static List<Badge> GetBadges()
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.Badges.ToList();
            }
        }

        public static List<Badge> GetSystemBadges()
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                List<Badge> list = ctx.Badges.Where(b => b.IsSystem).OrderBy(b => b.OrderId).ToList();
                return list;
            }
        }

        public static Badge GetBadge(Guid id)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.Badges.SingleOrDefault(p => p.Id == id);
            }
        }

        public static bool SaveBadge(Badge badge, bool isnew)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                badge.LastEditDate = DateTime.Now;

                try
                {
                    ctx.Badges.Attach(badge);
                    if (isnew)
                    {
                        badge.CreatedDate = DateTime.Now;
                    }
                    ctx.ObjectStateManager.ChangeObjectState(badge, isnew ? EntityState.Added : EntityState.Modified);

                    return ctx.SaveChanges() > 0;
                }
                catch (OptimisticConcurrencyException exOpt)
                {
                    ctx.Refresh(RefreshMode.ClientWins, badge);

                    return ctx.SaveChanges() > 0;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
}
